import { http, HttpResponse } from "msw";
import { type User } from "@/mocks/user/user-type";
import { createUserList } from "@/mocks/user/user-data";

export const user = [
  // 用户登录接口
  http.post("/api/user/login", async ({ request }) => {
    const body = (await request.json()) as User;
    // 获取请求体携带过来的用户名与密码
    const { username, password } = body;
    // 调用获取用户信息函数,用于判断是否有此用户
    const checkUser = createUserList().find((item) => {
      return item.username === username && item.password === password;
    });
    // 没有用户返回失败信息
    if (!checkUser) {
      return HttpResponse.json({
        code: 201,
        data: { message: "账号或者密码不正确" },
      });
    }
    // 如果有返回成功信息
    const { token } = checkUser;
    return HttpResponse.json({
      code: 200,
      data: token,
    });
  }),
  // 获取用户信息
  http.get("/api/user/info", async ({ request }) => {
    // 获取请求头中的token
    const token = request.headers.get("Authorization");
    // 如果没有token返回失败信息
    if (!token) {
      return HttpResponse.json({
        code: 201,
        data: { message: "token不存在" },
      });
    }
    //查看用户信息是否包含有次token用户
    const checkUser = createUserList().find((item) => item.token === token);
    //没有返回失败的信息
    if (!checkUser) {
      return HttpResponse.json({
        code: 201,
        data: { message: "获取用户信息失败" },
      });
    }
    // 如果有token返回成功信息
    return HttpResponse.json({
      code: 200,
      data: { ...checkUser },
    });
  }),
];
